package com.zorn.core.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class RecordUtils {

	/**
	 * 抽取集合中符合条件字段相应值的记录
	 * @param records 记录集合
	 * @param field 条件字段
	 * @param value 相应值
	 * @return 符合条件的记录集合
	 */
	public static List<Map<String, Object>> pluck(List<Map<String, Object>> records, String field, Object value) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Map<String, Object> record;

		for (Iterator<Map<String, Object>> iterator = records.iterator(); iterator.hasNext();) {
			record = iterator.next();
			if (record.get(field).equals(value)) result.add(record);
		}

		return result;
	}

	public static Map<String, List<Map<String, Object>>> group(List<Map<String, Object>> records, String groupField) {
		Map<String, List<Map<String, Object>>> groups = new HashMap<String, List<Map<String, Object>>>();
		Map<String, Object> rec;
		String key = null;

		for (Iterator<Map<String, Object>> iterator = records.iterator(); iterator.hasNext();) {
			rec = iterator.next();
			key = rec.get(groupField).toString();
			if (!groups.containsKey(key)) {
				groups.put(key, new ArrayList<Map<String, Object>>());
			}
			groups.get(key).add(rec);
		}

		return groups;
	}

	public static List<Map<String, Object>> sortASC(List<Map<String, Object>> records, String sortField) {
		Map<String, Object> x, y;
		int size = records.size();

		for (int i = size; i > 0; i--) {
			for (int j = size - 1; j > 0; j--) {
				x = records.get(j);
				y = records.get(j - 1);
				if (x.get(sortField).toString().compareTo(y.get(sortField).toString()) < 0) {
					records.set(j, y);
					records.set(j - 1, x);
				}
			}
		}
		return records;
	}

	public static List<Map<String, Object>> sortDESC(List<Map<String, Object>> records, String sortField) {
		Map<String, Object> x, y;
		int size = records.size();

		for (int i = size; i > 0; i--) {
			for (int j = size - 1; j > 0; j--) {
				x = records.get(j);
				y = records.get(j - 1);
				if (x.get(sortField).toString().compareTo(y.get(sortField).toString()) > 0) {
					records.set(j, y);
					records.set(j - 1, x);
				}
			}
		}
		return records;
	}

}
